#include "class.h"
#include "dbmanager.h"
#include <QTableWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QInputDialog>
#include <QMessageBox>
#include <mysql.h>

ClassManager::ClassManager(QWidget* parent) : QWidget(parent) {
    auto lay = new QVBoxLayout(this);
    auto btnLay = new QHBoxLayout;

    m_table = new QTableWidget(0, 3);
    m_table->setHorizontalHeaderLabels({"ID", "班级名称", "学生人数"});
    m_table->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_table->setEditTriggers(QAbstractItemView::NoEditTriggers);

    btnAdd  = new QPushButton("添加班级");
    btnEdit = new QPushButton("修改班级");
    btnDel  = new QPushButton("删除班级");

    btnLay->addWidget(btnAdd);
    btnLay->addWidget(btnEdit);
    btnLay->addWidget(btnDel);
    btnLay->addStretch();

    lay->addLayout(btnLay);
    lay->addWidget(m_table);

    connect(btnAdd,  &QPushButton::clicked, this, &ClassManager::onAdd);
    connect(btnEdit, &QPushButton::clicked, this, &ClassManager::onEdit);
    connect(btnDel,  &QPushButton::clicked, this, &ClassManager::onDelete);

    refresh();
}

void ClassManager::refresh() {
    m_table->setRowCount(0);
    MYSQL_RES* res = DBManager::instance().query(
        "SELECT c.id, c.name, "
        "IFNULL((SELECT COUNT(*) FROM student s WHERE s.class_id=c.id), 0) "
        "FROM class c ORDER BY c.id"
        );
    if (!res) return;

    while (MYSQL_ROW row = mysql_fetch_row(res)) {
        int r = m_table->rowCount();
        m_table->insertRow(r);
        m_table->setItem(r, 0, new QTableWidgetItem(row[0]));
        m_table->setItem(r, 1, new QTableWidgetItem(row[1]));
        m_table->setItem(r, 2, new QTableWidgetItem(row[2]));
    }
    mysql_free_result(res);
    LOG << "班级列表刷新完成，共" << m_table->rowCount() << "个班级";
}

void ClassManager::onAdd() {
    bool ok;
    QString name = QInputDialog::getText(this, "添加班级", "班级名称：", QLineEdit::Normal, "", &ok);
    if (!ok || name.trimmed().isEmpty()) return;

    QString sql = QString("INSERT INTO class (name) VALUES ('%1')").arg(name.trimmed());
    if (DBManager::instance().exec(sql)) {
        refresh();
    } else {
        QMessageBox::warning(this, "错误", "添加失败，可能班级名重复");
    }
}

void ClassManager::onEdit() {
    int row = m_table->currentRow();
    if (row < 0) { QMessageBox::information(this, "", "请先选择一个班级"); return; }

    QString id = m_table->item(row, 0)->text();
    QString oldName = m_table->item(row, 1)->text();

    bool ok;
    QString name = QInputDialog::getText(this, "修改班级", "新名称：", QLineEdit::Normal, oldName, &ok);
    if (!ok || name.trimmed().isEmpty()) return;

    QString sql = QString("UPDATE class SET name='%1' WHERE id=%2")
                      .arg(name.trimmed()).arg(id);
    if (DBManager::instance().exec(sql)) {
        refresh();
    }
}

void ClassManager::onDelete() {
    int row = m_table->currentRow();
    if (row < 0) { QMessageBox::information(this, "", "请先选择一个班级"); return; }

    QString id = m_table->item(row, 0)->text();
    QString count = m_table->item(row, 2)->text();

    if (count.toInt() > 0) {
        QMessageBox::warning(this, "禁止删除", "该班级还有学生，不能删除！");
        return;
    }

    if (QMessageBox::question(this, "确认", "确定删除该班级吗？") == QMessageBox::Yes) {
        QString sql = QString("DELETE FROM class WHERE id=%1").arg(id);
        DBManager::instance().exec(sql);
        refresh();
    }
}
